package com.kaoqin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.kaoqin.code.util.AuthorUtils;
import com.kaoqin.code.util.DESUtils;
import com.kaoqin.model.User;
import com.kaoqin.service.UserService;

@Controller
@RequestMapping("user")
public class UserController {
	@Autowired
	private UserService userService;

	/**
	 * 登录
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request,String username,String password,Model model) throws Exception {
		DESUtils des = AuthorUtils.getDESToken();
		String currentIp = request.getAttribute("currentIp").toString();
		User user = new  User();
		user.setUserIp(currentIp);
		user.setUserName(username);
		user.setUserPassword(des.encrypt(password));
		user.setLimitSql(" limit 0,1");
		User findByIp = userService.findByIp(user);
		if(findByIp!=null) {//登录成功
			HttpSession session = request.getSession();
			session.setAttribute("token",findByIp.getUserPassword());
			return "redirect:/sign/list";
		}
		model.addAttribute("msg","用户名或密码错误");
		return "/login/login";
	}
	@RequestMapping("/quit")
	public String quit(HttpServletRequest request) throws Exception {
		HttpSession session = request.getSession();
		Object tokenObj = session.getAttribute("token");
		if(tokenObj!=null) {
			session.setAttribute("token", "");
		}
		return "redirect:/sign/list";
	}
}
